#!/usr/bin/ruby

# This program manages multiple git repos using a YAML file and ruby-git.
# Each command line argument is just a command to the script.
#
# Author:: Erik Rainey (mailto:erik.rainey@gmail.com)
# Copyright:: Copyright (c) 2013 Erik Rainey
# License:: Apache 2.0

require 'yaml'
require 'rubygems'
require 'git'
require 'logger'

def affected_files(files)
    files.each do |item|
        # Each item is an array (why?) we only care about the strings
        item.select{|i| i.class == String}.each do |file|
           puts "\t\t#{file}"
        end
    end
end

if $0 == __FILE__
    fcfg = File.open('.mpgit')
    exit(-1) if fcfg == nil
    cfg = YAML::load(fcfg)
    cfg['paths'].each do |path|
    branch = cfg['branches'][path]
    remote = cfg['remotes'][path]
    # defaults in case it was not set
    branch ||= 'master'
    remote ||= 'origin'
    puts "Git in #{path}:#{branch}"
    g = Git.open(path) #,:log=>Logger.new(STDOUT))
        ARGV.each do |cmd|
            if cmd == 'status' 
                puts "\t#{g.status.changed.length} changed files"
                affected_files(g.status.changed)
                puts "\t#{g.status.added.length} added files"
                affected_files(g.status.added)
                puts "\t#{g.status.deleted.length} deleted files"
                affected_files(g.status.deleted)
                puts "\t#{g.status.untracked.length} untracked files"
                affected_files(g.status.untracked)
            end
            if cmd == 'update'
                remote_branch = "#{remote}/#{branch}"
                # this will merge with the currently checked out branch
                m = g.pull(g.remote(remote),g.branch(remote_branch))
                puts "#{m}"
            end
            if cmd == 'fetch'
                g.fetch(g.remote(remote))
            end
        end
    end
end
